# -*- coding: utf-8 -*-
import gitee_package
import log_package
import ini_package
from playwright_package import os_package
from gitee_package import re
from playwright_package import time_package
import playwright_package
import excel_package


# 获取gitee数据
def get_gitee_data():
    global ini_opt, ini_opt_school
    try:
        # 连接gitee获取基本数据
        gitee_opt = gitee_package.Gitee_Option('https://gitee.com/zl_b/file_config.git',
                                               "06fbfe091fc755b51084d86966a14cc6")
        main_repo_data = gitee_opt.list_all_files_and_folders('金牛区相关信息')

        # 获取ini数据
        url = main_repo_data.get("重要配置.ini")
        if url:
            da = gitee_opt.get_gitee_repo_file(url)
            if da:
                ini_opt.read_ini_string(da)
                log_opt.write_success(f'成功获取gitee数据，【重要配置.ini】信息成功！')
                url_2 = main_repo_data.get("学校配置.ini")
                if url_2:
                    da = gitee_opt.get_gitee_repo_file(url_2)
                    if da:
                        ini_opt_school.read_ini_string(da)
                        log_opt.write_success(f'成功获取gitee数据，【学校配置.ini】信息成功！')
                        return True
                    else:
                        raise Exception('获取【学校配置.ini】信息失败！')
                else:
                    raise Exception('未找到-【学校配置.ini】！')
            else:
                raise Exception('获取【重要配置.ini】信息失败！')
        else:
            raise Exception('未找到-【重要配置.ini】！')


    except Exception as e:
        log_opt.write_error(f'获取gitee出现错误{e}')
        return False


# 数据清洗
def clean_data(file_path):
    """
    清洗数据
    :param ex:excel对象
    :return:
    """
    ex = excel_package.Excel_Option(file_path)
    ex.open_file()
    try:
        for sheet in ex.list_sheets():
            '''删除所有格式'''
            ex.clear_region_format(sheet)

            '''文本居中'''
            ex.modify_region_alignment(sheet, horizontal="center", vertical="center")

            '''删除None列'''
            while True:
                k = ex.get_sheet_headers(sheet)
                # print(k)
                if None in k:

                    # print(sheet)
                    ex.delete_column(sheet, k.index(None) + 1)
                else:
                    break

            '''删除None行'''
            # 配置行
            k = ex.get_column_values(sheet, "A")
            # 如果第一列数据是有行是None就要删除这一行
            while True:
                k = ex.get_column_values(sheet, "A")
                if None in k:
                    # print(k)
                    ex.delete_row(sheet, k.index(None) + 1)
                    # print(sheet)
                else:
                    break

            '''重置索引'''
            rows = ex.get_sheet_max_rows(sheet)
            p = 1
            for i in range(2, rows + 1):
                ex.modify_cell_value(sheet, i, 1, p)
                p += 1
        ex.save_file()
        ex.close_file()
        return True
    except Exception as e:
        ex.close_file()
        return False


# 分割学校名称
def extract_school_name(item):
    if "竞赛" in item:
        match = re.search(r'(\w+)竞赛', item)
        if match:
            return match.group(1)
        else:
            return None

    elif "普" in item:
        match = re.search(r'(\w+)普', item)
        if match:
            return match.group(1)
        else:
            return None
    else:
        return None


# 分割年级
def extract_text_by_nodes(text):
    patterns = [r'(.*?)(普|竞赛)(.*)', r'(.*)(普|竞赛)$']
    for pattern in patterns:
        match = re.search(pattern, text)
        if match:
            return match.group(1), match.group(2), match.group(3)
    return "", "", ""


if __name__ == '__main__':
    print('''请输入目标文件(xlsx)路径：''')
    user_file_path = str(input())
    print("#"*60)
    # print('''请选择插入模式\n[0]:全部sheet都要插入\n[1]:只插入普教班\n[2]:只插入竞赛班\n为空或者其他值默认为0''')
    # user_select_mode = input('请输入您要选择的模式：\n')
    # try:
    #     user_select_mode = int(user_select_mode)
    # except Exception as e:
    #     user_select_mode = 0
    # print("#" * 60)
    # print('''请输入插入定位表头名称(例如：考勤数据,默认插在考勤数据之后)：''')
    # user_location_name = str(input())
    # print("#"*60)
    # print('''请输入新表头名称(例如：考勤数据)：''')
    # user_new_header_name = str(input())
    # print("#"*60)
    # 初始化
    time_opt = time_package.Time_Option()
    time_opt.timesleep(0.5)
    time_opt.start_timing()
    log_opt = log_package.Logging_Option()
    log_opt.write_info('正在初始化...')
    ini_opt = ini_package.Config_Option()
    ini_opt_school = ini_package.Config_Option()
    os_opt = os_package.Os_Option()
    os_opt.make_file_folder('file')
    os_opt.make_file_folder('log')

    try:
        if not os_opt.get_isexist(user_file_path):
            raise Exception("用户输入路径发送错误，格式或路径不存在！")

        # 获取gitee数据
        log_opt.write_success('初始化成功！')
        log_opt.write_info('正在获取gitee数据...')
        if get_gitee_data():
            log_opt.write_success('获取gitee数据成功！')
            clean_data(user_file_path)
            ex_main = excel_package.Excel_Option(user_file_path)
            ex_main.open_file()
            sheet_names = ex_main.list_sheets()
            if '竞赛模板' in sheet_names:
                sheet_names.remove('竞赛模板')
            if '普模板' in sheet_names:
                sheet_names.remove('普模板')

            try:
                for sheet in sheet_names:
                    # print(sheet)
                    # 计算出勤率
                    cq = ex_main.get_sheet_headers(sheet)[ex_main.get_sheet_headers(sheet).index('考勤数据')+1:]
                    max_cq = len(cq)
                    # print(cq)
                    if max_cq>0:
                        for r in range(2,ex_main.get_sheet_max_rows(sheet)+1):
                            r_cql = []
                            for c in cq:
                                c1 = ex_main.get_sheet_headers(sheet).index(c)+1
                                if ex_main.get_cell_value(sheet,r,c1) == '出勤':
                                    r_cql.append(True)
                            # print(r_cql)
                            cql  =  len(r_cql)/max_cq
                            ex_main.modify_cell_value(sheet,r,ex_main.get_sheet_headers(sheet).index('考勤数据')+1,cql)
                            ex_main.modify_region_value_format(sheet, r,ex_main.get_sheet_headers(sheet).index('考勤数据')+1,
                                                               r,ex_main.get_sheet_headers(sheet).index('考勤数据')+1,
                                                               '0.00%')
                            ex_main.modify_region_font_format(sheet, r,
                                                               ex_main.get_sheet_headers(sheet).index('考勤数据') + 1,
                                                               r,
                                                               ex_main.get_sheet_headers(sheet).index('考勤数据') + 1,
                                                                color='ff0000')

                ex_main.save_file()


            except Exception as e:
                print(e)
                raise Exception('在表中插入数据失败!')
        else:
            raise Exception('获取gitee数据失败!')
    except Exception as e:
        log_opt.write_error(f'程序异常：{e}')
    finally:
        log_opt.write_info(f'程序用时：{time_opt.end_timing()}')
        time_opt.timesleep(3)
